package gui.VPOfOperations;

import entities.FailSet;
import entities.ProductionOrder;
import entities.QCReport;
import entities.RequestParameters;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.miginfocom.swing.MigLayout;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;

import utilities.PrintActionListener;

import javax.swing.border.EtchedBorder;
import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *Report GUI
 */
public class VPOfOperationsRawMaterialsReport extends JPanel
{
	private JPanel mainPanel;
	private JScrollPane chartTableScroll;
	public DefaultTableModel model;
	private DefaultCategoryDataset dataset ;

	private VPOfOperationsTabbedPane tabbedpane;
	private JTable table;
	
	public VPOfOperationsRawMaterialsReport(VPOfOperationsTabbedPane myTabbedPane, RequestParameters parameters) 
	{
		setBackground(new Color(173, 216, 230));
		this.tabbedpane = myTabbedPane;
		setLayout(new MigLayout("", "[::100px,grow][grow,fill][::100px,grow]", "[][grow][][]"));
		
		mainPanel = new JPanel(){	@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		mainPanel.setBackground(new Color(173, 216, 230));
		mainPanel.setBorder(new TitledBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(59, 59, 59)), "\u05D3\u05D5\u05D7 \u05E4\u05E1\u05D9\u05DC\u05D5\u05EA \u05DC\u05E4\u05D9 \u05D0\u05E6\u05D5\u05D5\u05EA \u05D7\u05D5\u05DE\u05E8 \u05D2\u05DC\u05DD "  + new Date(parameters.getStartTimestamp().getTime()) + " - " + new Date(parameters.getEndTimestamp().getTime()), TitledBorder.CENTER, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(mainPanel, "cell 1 1,growx,aligny center");
		mainPanel.setLayout(new MigLayout("", "[][grow,fill][]", "[][::200px][grow]"));
		
		JScrollPane scrollPane = new JScrollPane();
		mainPanel.add(scrollPane, "cell 1 1,growx,aligny center");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05E1\u05D4\"\u05DB \u05E2\u05D3\u05E9\u05D5\u05EA", "\u05E1\u05D8\u05D9\u05D9\u05EA \u05D3\u05D9\u05D5\u05E4\u05D8\u05E8 \u05D0\u05D7\u05E8\u05EA", "\u05E1\u05D8\u05D9\u05D9\u05EA \u05D3\u05D9\u05D5\u05E4\u05D8\u05E8 1.0+", "\u05E1\u05D8\u05D9\u05D9\u05EA \u05D3\u05D9\u05D5\u05E4\u05D8\u05E8 0.5+", "\u05E1\u05D8\u05D9\u05D9\u05EA \u05D3\u05D9\u05D5\u05E4\u05D8\u05E8 0.5-", "\u05E1\u05D8\u05D9\u05D9\u05EA \u05D3\u05D9\u05D5\u05E4\u05D8\u05E8 1.0-", "\u05D0\u05E6\u05D5\u05D5\u05EA \u05D7\u05D5\u05DE\u05E8 \u05D2\u05DC\u05DD"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(1).setPreferredWidth(116);
		table.getColumnModel().getColumn(2).setPreferredWidth(125);
		table.getColumnModel().getColumn(3).setPreferredWidth(149);
		table.getColumnModel().getColumn(4).setPreferredWidth(126);
		table.getColumnModel().getColumn(5).setPreferredWidth(135);
		table.getColumnModel().getColumn(6).setPreferredWidth(128);
		table.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		
	
		
		JButton closeButton = new JButton("סגור דוח");
		closeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		closeButton.setIcon(new ImageIcon(VPOfOperationsRawMaterialsReport.class.getResource("/graphics/back.png")));
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				// get tab index
				tabbedpane.remove(tabbedpane.getSelectedIndex());
				// remove tab
			}
		});
		add(closeButton, "flowx,cell 1 2,alignx center");
		
		JLabel lblNewLabel = new JLabel("               ");
		add(lblNewLabel, "cell 1 2");
		
		JButton printButton = new JButton("יצא לאקסל");
		printButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		printButton.setIcon(new ImageIcon(VPOfOperationsRawMaterialsReport.class.getResource("/graphics/excel.png")));
		printButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) 
			{
//JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(mainPanel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(mainPanel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start(); 
			}
		});
		add(printButton, "cell 1 2,alignx center");
		
		
		  
	}
	
	public void setVariables(ArrayList<Object> response) 
	{
		// index 0 is the flag
		// index 1 is the counter
		// index 2 is the data
		

		model = (DefaultTableModel) table.getModel();
		

			int rowCount = (int) response.get(1);
			
			 

		
			
			  dataset = new DefaultCategoryDataset();
			  
			 for (int i=1; i<=((int)response.get(1));i++)
		     {
				 QCReport report = (QCReport)response.get(i+1);
				 model.addRow(new Object[]{report.getFailSetFlag(),report.getDeviationCountElse(),report.getDeviationCountPlus10(),report.getDeviationCountPlus05(),report.getDeviationCountMinus05(),report.getDeviationCountMinus10(),report.getRawMaterialID()});
				 
		     }
			 
			 
			 table.getColumnModel().getColumn(0).setPreferredWidth(130);
			 table.getColumnModel().getColumn(1).setPreferredWidth(130);
			 table.getColumnModel().getColumn(2).setPreferredWidth(130);
			 table.getColumnModel().getColumn(3).setPreferredWidth(130);
			 table.getColumnModel().getColumn(4).setPreferredWidth(130);
			 table.getColumnModel().getColumn(5).setPreferredWidth(130);
			 table.getColumnModel().getColumn(6).setPreferredWidth(130);
			 
			       	
			
			 for (int row =0 ; row < table.getRowCount() ; row++)
			 {
				 // dev -1.0
				 String material = model.getValueAt(row, 6).toString();        	
				 String deviation = "סטייה ב1.0-";	      
				 Number count = Integer.parseInt(model.getValueAt(row, 5).toString());	 
				 
				 dataset.addValue(count,deviation,material);
				        
				 // dev -0.5
				 material = model.getValueAt(row, 6).toString();        	
				 deviation = "סטייה ב0.5-";	      
				 count = Integer.parseInt(model.getValueAt(row, 4).toString());	 
				 
				 dataset.addValue(count,deviation,material); 				 
				 
				 // dev +0.5
				 material = model.getValueAt(row, 6).toString();        	
				 deviation = "סטייה ב0.5+";	      
				 count = Integer.parseInt(model.getValueAt(row, 3).toString());	 
				 
				 dataset.addValue(count,deviation,material); 				 
				 
				 
				 // dev +1.0
				 material = model.getValueAt(row, 6).toString();        	
				 deviation = "סטייה ב1.0+";	      
				 count = Integer.parseInt(model.getValueAt(row, 2).toString());	 
				 
				 dataset.addValue(count,deviation,material); 	
				 
				 // dev else
				 material = model.getValueAt(row, 6).toString();        	
				 deviation = "סטייה אחרת";	      
				 count = Integer.parseInt(model.getValueAt(row, 1).toString());	 
				 
				 dataset.addValue(count,deviation,material); 					 
				 

			 }
			 
			        // create Chart
			        
			      
			      //  JFreeChart chart = ChartFactory.createBarChart(
			        JFreeChart chart = ChartFactory.createStackedBarChart3D(
			        		((TitledBorder)mainPanel.getBorder()).getTitle(), // chart title
			        		"חומר גלם", // domain axis label
			        		"פסילות", // range axis label
			        		dataset, // data
			        		PlotOrientation.VERTICAL, // orientation
			        		true, // include legend
			        		true, // tooltips?
			        		false // URLs?
			        		);

			        
			    
			        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
			      //  plot.setRenderer(new StackedBarRenderer3D(true));
			        BarRenderer renderer =  (BarRenderer) plot.getRenderer();
			        DecimalFormat format = new DecimalFormat("##.#");
			        renderer.setItemLabelGenerator((CategoryItemLabelGenerator) new StandardCategoryItemLabelGenerator("{2}",format));
			        renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER));
			        renderer.setItemLabelsVisible(true);
			  
			        
			        
			        
			        
		        CategoryAxis xAxis = (CategoryAxis)plot.getDomainAxis();
		        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		        
//		        renderer.setSeriesItemLabelsVisible(0, true);

		        //renderer.
		        // renderer.setItemMargin(0.0);
		        
		        
		        ChartPanel chartPanel = new ChartPanel(chart, false);
		        chartPanel.setMouseWheelEnabled(true);
		      //  chartPanel.setPreferredSize(new Dimension(500, 270));
		        
		        chartTableScroll = new JScrollPane(chartPanel);
		        mainPanel.add(chartTableScroll, "cell 1 2,grow");
		       // mainPanel.add(chartPanel, "cell 1 2,grow");
		       // chartPanel.setVisible(true);
		        

			
		
	}

	

	
	
	 public TableModel getModel(ArrayList<Object> response)
	 {
		 
	        Object[][] ss=new Object[response.size()-2][4];
	       
	        
	        for (int i=1; i<=((int)response.get(1));i++)
	        {
	        	
	        	ProductionOrder report = (ProductionOrder)response.get(i+1);
	        	ss[i-1] = new Object[]{report.getQuantity(),Integer.parseInt(report.getFails()),report.getDiopter(),report.getType(),report.getProductFamily(),report.getOrderID()};
	        }
	        
	       
	        FailQuantitiesReportTable dm= new FailQuantitiesReportTable(ss,new String[] {"Quantity","Fails","Diopter","Type","ProductFamily","OrderID"});
	        return dm;
	    }
	 
	 
	 
		@Override
		public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight(); 
        GradientPaint gp = new GradientPaint(
                0, 0, color1,
                0, h, color2);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        }
	 
}